package com.magnate.software.spring.boot.web.util;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

/**
 * json web token utils
 * <p>
 * Created by wangyang on 2017/4/28.
 */
public class JsonWebTokenUtils {

    public static final String JWT_ID = "jwt";
    public static final String JWT_SECRET = "hong1mu2zhi3ruan4jian5";
    public static final int JWT_TTL = 60 * 60 * 1000;  //millisecond
    public static final int JWT_REFRESH_INTERVAL = 55 * 60 * 1000;  //millisecond
    public static final int JWT_REFRESH_TTL = 12 * 60 * 60 * 1000;  //millisecond


    private static String jianshu = "mykey";

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey() {
        String stringKey = jianshu + JWT_SECRET;
        byte[] encodedKey = Base64.getDecoder().decode(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 生成subject信息
     *
     * @param params 参数
     * @return
     */
    public static String generalSubject(Map<String, Object> params) {
        JSONObject jo = new JSONObject();
        for (String key : params.keySet()) {
            jo.put(key, params.get(key));
        }
        return jo.toJSONString();
    }

    /**
     * 创建jwt
     *
     * @param claims
     * @return
     * @throws Exception
     */
    public static String buildJsonWebToken(Claims claims) throws Exception {
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder();
        //builder.setHeaderParam("typ","JWT");
        //builder.setId(claims.getId()); // JWT id
        //builder.setSubject(claims.getSubject()); // 主题
        builder.setIssuer("acl.platform.com"); // 发行者
        builder.setAudience(claims.getAudience()); // 听众
        builder.setIssuedAt(claims.getIssuedAt()); // 发行时间
        if (claims.getExpiration() != null) {
            builder.setExpiration(claims.getExpiration()); // 过期时间
        }
        builder.signWith(SignatureAlgorithm.HS256, key); // 加密算法
        return builder.compact();
    }

    /**
     * 解密jwt
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims decodeJsonWebToken(String jwt) throws Exception {
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }

    public static void main(String[] args) {
        try {
            System.out.println(JsonWebTokenUtils.generalKey());
            Date date = new Date();
            Claims claims = new DefaultClaims();
            claims.setId("jwtId");
            claims.setAudience("13601242050");
            claims.setSubject("subject");
            claims.setIssuedAt(date);
            claims.setExpiration(new Date(date.getTime() + 1000000));

            String msg = JsonWebTokenUtils.buildJsonWebToken(claims);
            System.out.println(msg);

            //String msg = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqd3RJZCIsImlzcyI6ImFjbC5wbGF0Zm9ybS5jb20iLCJhdWQiOiIxMzYwMTI0MjA1MCIsImlhdCI6MTQ5MzcwNTUzNSwic3ViIjoic3ViamVjdCIsImV4cCI6MTQ5MzcwNjUzNX0.M__6VsuLRBOfWsQ0Lfts6yn1HO_lPEvbZLHnc0xzesE";

            claims = JsonWebTokenUtils.decodeJsonWebToken(msg);
            System.out.println(claims.getAudience());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
